import { MenuFoldOutlined } from '@ant-design/icons';
import type Umi from 'umi';
import { connect, DefaultFormValue } from 'umi';
import { useRef, useState, useEffect } from 'react';
import { FooterToolbar, ProForm } from '@ant-design/pro-components';
import { Button, Card, Space, Anchor, Spin, message } from 'antd';
import { history } from 'umi';
import useDetailType from '@/hooks/useDetailType';
import useDispatcher from '../components/hooks/useDispatcher';
import { PageContainer } from '@ant-design/pro-components';
import type { ProFormInstance } from '@ant-design/pro-components';
import {
  profileEdit,
  profileSearch,
  getActivityReusableList,
  getActivityStoreList,
  getActivityDateList,
  getActivityTimeList,
  getActivityDmonthList,
  getActivityDweekList,
  getNeedGenasynfile,
} from '@/services/profile';
import { beforeSaveValidate, convertValueForSave, convertValueForDetail } from './indexTool';
import BasicInfo from '../components/basicInfo';
import ClassfyDescription from '../components/classfyDescription';
import FinanceInfo from '../components/financeInfo';
import WriteOff from '../components/writeOff';
import KeyInfo from '../components/keyInfo';
import MemberInfo from '../components/memberInfo';

import styles from './style.less';

interface IParams {
  type?: string;
  id?: string;
}

type ProfileFrom = Partial<API.RealProfileInfo> & {};

type PropsFromModel = Umi.TProfileModelState;

interface IEditorProps extends PropsFromModel {
  profile: PropsFromModel;
}

const { Link } = Anchor;
const ProfileDetail: React.FC<IEditorProps> = (props) => {
  console.log('profile----', props.profile);
  const { formValue } = props.profile;
  const { isAdd, isModify, isRead, params, pathname } = useDetailType<IParams>();
  const formRef = useRef<ProFormInstance>();
  const [showAnchor, setShowAchor] = useState<boolean>(true);
  const [spinning, setSpinning] = useState<boolean>(false);
  const dispatch = useDispatcher();

  const goToList = () => {
    history.push('/profile/detail/list');
    formRef.current?.setFieldsValue({ ...DefaultFormValue });
    dispatch('setFormValue', { ...DefaultFormValue });
  };

  useEffect(() => {
    formRef.current?.setFieldsValue({ ...DefaultFormValue });
    dispatch('resetFormValue');
  }, []);

  // 表单滚动到第一个报错处（antd）
  const scrollToError = () => {
    document
      .querySelector('.ant-form-item-has-error')
      ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
    document
      .querySelector('.ant-form-item-explain-error')
      ?.scrollIntoView({ behavior: 'smooth', block: 'center' });
  };

  // 限制使用规则明细 ---查询各个条件下不同结果
  const queryAgainRealProfileInfo = async (value: API.RealProfileInfo) => {
    // getNeedGenasynfile
    if (value.profileStatus && value.profileStatus === '已提交' && isModify) {
      const { code, data } = await getNeedGenasynfile({
        activityId: value.activityId,
      });
      if (code === 200 && data) {
        formRef.current?.setFieldsValue({ needGenasynfile: data });
        dispatch('setFormValue', { needGenasynfile: data });
      }
    }

    if (value.useMarketings && value.useMarketings.length > 0) {
      if (value.useMarketings.includes('REUSABLECOUNTLIMIT')) {
        const { code, data } = await getActivityReusableList({
          activityId: value.activityId,
        });
        if (code === 200) {
          formRef.current?.setFieldsValue({ reusableCountValue: data });
          dispatch('setFormValue', { reusableCountValue: data });
        }
      }
      if (value.useMarketings.includes('STORELIMIT')) {
        const { code, data } = await getActivityStoreList({
          activityId: value.activityId,
        });
        if (code === 200) {
          formRef.current?.setFieldsValue({ storeValues: data.join(',') || '' });
          dispatch('setFormValue', { storeValues: data.join(',') || '' });
        }
      }
      if (value.useMarketings.includes('DATELIMIT')) {
        const { code, data } = await getActivityDateList({
          activityId: value.activityId,
        });
        if (code === 200 && data) {
          const arr: string[] = [];
          data.forEach((item: any) => {
            arr.push(item.startTime + '--' + item.endTime);
          });
          formRef.current?.setFieldsValue({ dateLimitValue: arr.join(',') || '' });
          dispatch('setFormValue', { dateLimitValue: arr.join(',') || '' });
        }
      }
      if (value.useMarketings.includes('TIMELIMIT')) {
        const { code, data } = await getActivityTimeList({
          activityId: value.activityId,
        });
        if (code === 200 && data) {
          const arr: string[] = [];
          data.forEach((item: any) => {
            arr.push(item.startTime + '--' + item.endTime);
          });
          formRef.current?.setFieldsValue({ timeLimitValue: arr.join(',') || '' });
          dispatch('setFormValue', { timeLimitValue: arr.join(',') || '' });
        }
      }
      if (value.useMarketings.includes('DWEEKLIMIT')) {
        const { code, data } = await getActivityDweekList({
          activityId: value.activityId,
        });
        if (code === 200 && data) {
          formRef.current?.setFieldsValue({ dweekLimitValue: data });
          dispatch('setFormValue', { dweekLimitValue: data });
        }
      }
      if (value.useMarketings.includes('DMONTHLIMIT')) {
        const { code, data } = await getActivityDmonthList({
          activityId: value.activityId,
        });
        if (code === 200 && data) {
          formRef.current?.setFieldsValue({ dmonthLimitValue: data });
          dispatch('setFormValue', { dmonthLimitValue: data });
        }
      }
    }
    // value.
  };

  // 新增或者编辑  表单内容-初始化
  const getDetail = async () => {
    if (params.id && (isModify || isAdd)) {
      setSpinning(true);
      // 编辑
      const { code, data } = await profileSearch({
        activityIds: params.id,
      });
      if (code === 200 && data) {
        const info = data[0].realProfileInfo || {};
        queryAgainRealProfileInfo({ ...info });

        // 复制
        if (isAdd) {
          delete info.id;
          info.activityId = '';
          info.onlineCode = '';
          info.profileStatus = '填写中';
          info.needGenasynfile = ''; // 复制时初始化--发放标签
        }
        dispatch('setFormValue', convertValueForDetail({ ...info }));
        setTimeout(() => {
          setSpinning(false);
        });
        return {
          ...convertValueForDetail({ ...info }),
        };
      } else {
        setTimeout(() => {
          setSpinning(false);
        });
      }
    } else {
      // 表单初始化的值没有清空--问题修复
      dispatch('setFormValue', { ...DefaultFormValue });
      return { ...DefaultFormValue };
      // return { ...formValue };
    }
  };

  const onValueChange = (value: any) => {
    // const { getFieldValue, setFieldValue, setFieldsValue } = formRef.current!;
    console.log(value, 'onValueChange');
    if (value) {
      dispatch('setFormValue', value);
    }
  };

  const onFinish = async (value: Partial<API.RealProfileInfo>) => {
    console.log('onFinish---value', isAdd, isModify, value);
    console.log('convertValueForSave---formValue', {
      ...convertValueForSave({ ...formValue }, { ...value }),
    });

    if (!beforeSaveValidate({ ...formValue })) return;
    const Value = {
      scenarioDesc: null,
      realProfileInfo: {
        ...convertValueForSave({ ...formValue }, { ...value }),
      },
    };

    const { data, code } = await profileEdit(Value);
    if (code === 200 && data) {
      message.success('保存成功');
      goToList();
      // if (isAdd) {
      // }
    }
  };

  const handleCollAnchor = () => {
    setShowAchor(!showAnchor);
  };

  return (
    <div className={styles['detail-body']}>
      <Spin spinning={spinning}>
        {/* <Spin spinning={props.profile.length === 0}> */}
        <PageContainer>
          <div className={styles['rule-config-warp']}>
            <div className={styles['rule-left-wrap']}>
              <div className={styles['rule-left-title']}>
                <MenuFoldOutlined
                  className={styles['anchor-title-icon']}
                  onClick={handleCollAnchor}
                />
              </div>
              {showAnchor ? (
                <div className={styles['rule-anchor-warp']} onClick={(e) => e.preventDefault()}>
                  <Anchor offsetTop={50}>
                    <div className={styles['anchor-title']}>配置劵</div>
                    <div>
                      <Link href="#basic-info" title="基本信息" />
                      <Link href="#classfy-description" title="分类说明" />
                      <Link href="#finance-info" title="财务信息" />
                      <Link href="#write-off" title="发放与核销规则" />
                      <Link href="#key-info" title="键值信息" />
                      <Link href="#member-info" title="商城及会员卡包信息" />
                    </div>
                  </Anchor>
                </div>
              ) : null}
            </div>

            <Card className={styles['rule-content-warp']}>
              <ProForm<Partial<ProfileFrom>>
                // readOnly={isRead}
                formRef={formRef}
                layout="horizontal"
                labelCol={{ span: 4 }}
                wrapperCol={{ span: 20 }}
                scrollToFirstError
                onValuesChange={onValueChange}
                onFinishFailed={scrollToError}
                onFinish={onFinish}
                //@ts-ignore
                request={getDetail}
                submitter={{
                  searchConfig: {
                    resetText: '返回',
                  },
                  render: (_, dom) => (
                    <FooterToolbar
                      extra={
                        <div style={{ textAlign: 'center', padding: '5px 0' }}>
                          {isRead ? (
                            <Button onClick={goToList}>返回</Button>
                          ) : (
                            <Space>
                              <Button onClick={goToList}>返回</Button>
                              {dom[1]}
                            </Space>
                          )}
                        </div>
                      }
                    />
                  ),
                }}
              >
                <>
                  {/* 基本信息 */}
                  <BasicInfo formRef={formRef} profile={props.profile} />
                  {/* 分类说明 */}
                  <ClassfyDescription formRef={formRef} />
                  {/* 财务信息 */}
                  <FinanceInfo formRef={formRef} />
                  {/* 发放与核销规则 */}
                  <WriteOff formRef={formRef} />
                  {/* 键值信息 */}
                  <KeyInfo formRef={formRef} />
                  {/* 商城及会员卡包信息 */}
                  <MemberInfo formRef={formRef} />
                </>
              </ProForm>
            </Card>

            {/* rule-content-warp */}
            {/* <div style={{ flex: 1, background: 'white' }} /> */}
          </div>
        </PageContainer>
      </Spin>
    </div>
  );
};

export default connect(({ profile }: { profile: PropsFromModel }) => ({
  profile,
}))(ProfileDetail);
